import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:schedule_self_client/api/schedule_self_server/task.dart';
import 'package:schedule_self_client/api/schedule_self_server/task_api.dart';
import 'package:schedule_self_client/api/schedule_self_server/task_list_resp_v2.dart';
import 'package:schedule_self_client/common/simple_resp.dart';

class TaskListPageV2 extends StatefulWidget {
  const TaskListPageV2({super.key});

  @override
  State<TaskListPageV2> createState() => _TaskListPageV2State();
}

class _TaskListPageV2State extends State<TaskListPageV2> {
  final List<Task> _completeTasks = [];
  final List<Task> _incompleteTasks = [];
  bool _isLoading = false;
  bool _completeCollapseFlag = true;
  bool _incompleteCollapseFlag = true;

  @override
  void initState() {
    super.initState();
    _loadTaskList();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('待办事项'),
        actions: [
          IconButton(
              onPressed: () {
                setState(() {
                  showDialog(
                    context: context,
                    builder: (context) => const AlertDialog(
                      title: Text('装饰，点了没用...'),
                    ),
                  );
                });
              },
              icon: const Icon(Icons.more_vert)),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        child: Column(
          children: [
            InkWell(
              onTap: () {
                setState(() {
                  _incompleteCollapseFlag = !_incompleteCollapseFlag;
                });
              },
              child: Container(
                height: 36,
                child: Row(
                  children: [
                    _incompleteCollapseFlag
                        ? Icon(Icons.arrow_drop_down)
                        : Icon(Icons.arrow_right),
                    Expanded(
                      child: Text(
                        '未完成',
                        style: Theme.of(context).textTheme.titleLarge,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            if (_incompleteCollapseFlag)
              Column(
                children:
                    _incompleteTasks.map((it) => _buildTaskCard(it)).toList(),
              ),
            InkWell(
              onTap: () {
                setState(() {
                  _completeCollapseFlag = !_completeCollapseFlag;
                });
              },
              child: Container(
                height: 36,
                child: Row(
                  children: [
                    _completeCollapseFlag
                        ? Icon(Icons.arrow_drop_down)
                        : Icon(Icons.arrow_right),
                    Expanded(
                      child: Text(
                        '已完成',
                        style: Theme.of(context).textTheme.titleLarge,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            if (_completeCollapseFlag)
              Column(
                children:
                    _completeTasks.map((it) => _buildTaskCard(it)).toList(),
              )
          ],
        ),
      ),
    );
  }

  Widget _buildTaskCard(Task task) {
    DateTime startTime = DateTime.parse(task.startTime);
    DateFormat dateFormat =
        DateFormat('M月d日 E', Localizations.localeOf(context).languageCode);
    return Card(
      child: Row(
        children: [
          // IconButton(onPressed: () {}, icon: Icon(Icons.check_circle_outline)),
          IconButton(
              onPressed: () {
                _taskCompleteFlagChange(task);
              },
              icon: task.isComplete()
                  ? Icon(Icons.check_circle_outline)
                  : Icon(Icons.circle_outlined)),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(
                  height: 8,
                ),
                Text(
                  task.name,
                  style: TextStyle(
                      color: task.isComplete() ? Colors.grey : Colors.black,
                      decoration: task.isComplete()
                          ? TextDecoration.lineThrough
                          : null),
                ),
                SizedBox(
                  height: 4,
                ),
                Row(
                  children: [
                    Icon(Icons.calendar_today, size: 16),
                    SizedBox(
                      width: 4,
                    ),
                    Text(dateFormat.format(startTime)),
                  ],
                ),
                SizedBox(
                  height: 8,
                )
              ],
            ),
          ),
          IconButton(onPressed: () {}, icon: Icon(Icons.star_border))
        ],
      ),
    );
  }

  _taskCompleteFlagChange(Task task) async {
    SimpleResp simpleResp = await TaskApi.taskCompleteFlagChange(task.id);
    if (simpleResp.success) {
      setState(() {
        _loadTaskList();
      });
    }
  }

  _loadTaskList() async {
    if (_isLoading) {
      return;
    }
    setState(() {
      _isLoading = true;
    });
    try {
      TaskListRespV2 taskListRespV2 = await TaskApi.getTasksV2();
      _incompleteTasks.clear();
      _incompleteTasks
          .addAll(taskListRespV2.data.where((task) => !task.isComplete()));
      _completeTasks.clear();
      _completeTasks
          .addAll(taskListRespV2.data.where((task) => task.isComplete()));
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
}
